package cn.collin.commons.web.taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import org.hibernate.Session;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import cn.collin.commons.web.filter.OpenSessionInViewHibernateFilter;

/**
 * http://collincode.googlecode.com
 * 
 * @author collin.code@gmail.com
 * 
 */
public class HelperClassTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	String var;

	String clazz;

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}

	public void setVar(String var) {
		this.var = var;
	}

	@Override
	public int doStartTag() throws JspException {
		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		HibernateHelper dao = null;
		try {
			dao = (HibernateHelper) Class.forName(clazz).newInstance();
		} catch (InstantiationException e) {
			throw new JspException(e);
		} catch (IllegalAccessException e) {
			throw new JspException(e);
		} catch (ClassNotFoundException e) {
			throw new JspException(e);
		}
		Session session = (Session) TransactionSynchronizationManager
				.getResource(OpenSessionInViewHibernateFilter.SESSION_NAME);
		dao.setSession(session);
		pageContext.setAttribute(var, dao.execute(pageContext),
				PageContext.PAGE_SCOPE);
		return EVAL_PAGE;
	}

}
